package org.example.controller;

import org.apache.ibatis.annotations.Param;
import org.example.domain.User;
import org.example.service.impl.UserServiceImpl;
import org.example.untils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserServiceImpl userServiceImpl;

    @PostMapping("/login")
    public Result login(@RequestBody User user){
        User sqlUser=userServiceImpl.login(user);
        if(sqlUser==null){
            return new Result(201,"账号不存在",null);
        } else if(sqlUser.getRegisterStatus()==0){
            return new Result(201,"注册申请中",null);
        } else if(user.getPassword().equals(sqlUser.getPassword())){
            return new Result(200,"登入成功",sqlUser);
        } else {
            return new Result(201,"账号/密码错误",null);
        }
    }

    @PostMapping("/register")
    public Result register(@RequestBody() User user){
        Integer result=userServiceImpl.register(user);
        if(result==0){
            return new Result(201,"已注册",null);
        } else if(result==2) {
            return new Result(201,"申请中",null);
        } else {
            return new Result(200, "申请成功", null);
        }
    }

    @GetMapping("/searchByAccount")
    public Result searchByAccount(@Param("account") String account){
        User user= userServiceImpl.searchByAccount(account);
        if(user!=null&&user.getRegisterStatus()!=0){
            return new Result(200,"搜索成功",user);
        } else {
            return new Result(201,"学生不存在",null);
        }
    }

    @GetMapping("/deleteUserById")
    public Result deleteUserById(Integer id){
        userServiceImpl.deleteUserById(id);
        return new Result(200,"注销成功",null);
    }

    @PostMapping("/changeUserInfo")
    public Result changeUserInfo(@RequestBody() User user){
        userServiceImpl.changeUserInfo(user);
        return new Result(200,"修改成功",null);
    }

    @GetMapping("/changePassword")
    public Result changePassword(String oldPassword,String newPassword,Integer id){
        Integer result=userServiceImpl.changePassword(oldPassword,newPassword,id);
        if(result==0){
            return new Result(201,"旧密码错误",null);
        } else if(result==1){
            return new Result(200,"密码修改成功",null);
        } else{
            return new Result(201,"数据库更新失败",null);
        }
    }
}
